#include "cTime_t.h"

void cTime_t::setCurrentTime() 
{
	time_t time_t_Now = time(NULL);
	struct tm *tm_Now;
	tm_Now = localtime(&time_t_Now);
	setTime(tm_Now->tm_hour, tm_Now->tm_min, tm_Now->tm_sec);
}


bool cTime_t::setTime(const int& hour,const int& minute, const int& seconds) 
{
	if (!legalTime(hour, minute, seconds))
	{
		return false;
	}
	
	_minute = minute;
	_hour = hour;
	_seconds = seconds;
	return true;
}

bool cTime_t::legalTime(const int& hour,const int& minute, const int& seconds) 
{
	if (hour < 0 || hour > 23) 
	{
		return false;
	}

	if (minute < 0 || minute > 60) 
	{
		return false;
	}

	if (seconds < 0 || seconds > 60) 
	{
		return false;
	}

	return true;
}

cTime_t::cTime_t()
{
	setCurrentTime();
	_printFormat = 1;
}

cTime_t::cTime_t(const int &hour, const int &minute, const int &seconds)
{
	if (!legalTime(hour, minute, seconds)) 
	{
		setCurrentTime();
	}
	else 
	{
		_hour = hour;
		_minute = minute;
		_seconds = seconds;
	}
	_printFormat = 1;
}

bool cTime_t::setPrintFormat(const int &format) 
{
	if (format == 1 || format == 2) {
		_printFormat = format;
		return true;
	}
	return false;
}

int cTime_t::getPrintFormat() const
{
	return _printFormat;
}

cTime_t::cTime_t(const cTime_t& mycTime)
{
	_minute = mycTime.getMinutes();
	_hour = mycTime.getHour();
	_seconds = mycTime.getSeconds();
	_printFormat = mycTime.getPrintFormat();
}


const cTime_t& cTime_t::operator=(const cTime_t& other)
{
	if (this != &other)
	{
		_minute = other.getMinutes();
		_hour = other.getHour();
		_seconds = other.getSeconds();
	}

	return *this;
}

ostream& operator<<(ostream&  os, const cTime_t &t)
{
	if (t.getPrintFormat() == 1) {
		return os << setfill('0') << setw(2) << t.getHour() << ":" << setw(2) << t.getMinutes() << ":" << setw(2) << t.getSeconds();
	}
	
	char* designator = "AM";
	int printHour = t.getHour();
	if (printHour > 11) {
		designator = "PM";
		if (printHour > 12) {
			printHour = printHour - 12;
		}
	}
	return os << setfill('0') << setw(2) << printHour << ":" << setw(2) << t.getMinutes() << ":" << setw(2) << t.getSeconds() << " " << designator;
}

int cTime_t::getHour() const 
{
	return _hour;
}

int cTime_t::getSeconds() const 
{
	return _seconds;
}

int cTime_t::getMinutes() const 
{
	return _minute;
}

cTime_t operator+ (cTime_t& time1, const cTime_t& time2)
{
	int returnMinute, returnHour;
	
	returnMinute = (time1.getSeconds() + time2.getSeconds()) / 60;
	returnHour = (time1.getMinutes() + time2.getMinutes() + returnMinute) / 60;

	returnMinute = (returnMinute + time1.getMinutes() + time2.getMinutes()) % 60;
	returnHour = (returnHour + time1.getHour() + time2.getHour()) % 24;
	time1 = cTime_t(returnHour, returnMinute, (time1.getSeconds() + time2.getSeconds()) % 60);
	return time1;
}
